package ua.at.tsvetkov.samizdat.activities;

import ua.at.tsvetkov.samizdat.Const;
import ua.at.tsvetkov.samizdat.R;
import ua.at.tsvetkov.samizdat.fragments.FrgBooks;
import ua.at.tsvetkov.samizdat.fragments.FrgGenres;
import ua.at.tsvetkov.samizdat.services.SrvUpdate;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;

public class AcMainTablet extends Activity implements IMenuActivity {

	FrgBooks				fragmentBooks;
	FrgGenres			fragmentGenres;
	private Integer	currentGenresClickedPosition	= 1;
	private ProgressDialog	progressDialog;
	private MenuItem	sortByBall;
	private MenuItem	sortByDate;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_main_tablet);

		fragmentBooks = new FrgBooks();
		fragmentGenres = new FrgGenres();
		
		IntentFilter intentFilter = new IntentFilter(Const.BROADCAST_MESSAGE);
		registerReceiver(intentReceiver, intentFilter);

		Bundle args = new Bundle();
		args.putInt(Const.FRAGMENT_GENRES_CLICK_POSITION, 0);
		fragmentBooks.setArguments(args);

		ActionBar actionBar = getActionBar();
		actionBar.setDisplayHomeAsUpEnabled(true);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		FragmentManager fm = getFragmentManager();
		FragmentTransaction ft = fm.beginTransaction();
		if (isOrientationLanscape()) {
			ft.remove(fragmentGenres);
			ft.remove(fragmentBooks);
			ft.commit();
		} else {
			ft.remove(fragmentBooks);
			ft.remove(fragmentGenres);
			ft.commit();
		}
		fm.executePendingTransactions();
		super.onConfigurationChanged(newConfig);
		setContentView(R.layout.ac_main_tablet);

		FragmentManager fm2 = getFragmentManager();
		FragmentTransaction ft2 = getFragmentManager().beginTransaction();

		if (isOrientationLanscape()) {
			ft2.add(R.id.layout1, fragmentGenres);
			ft2.add(R.id.layout2, fragmentBooks);
			ft2.commit();
		} else {
			ft2.add(R.id.activity_main_tablet_parent_view, fragmentGenres);
			ft2.commit();
		}
		fm2.executePendingTransactions();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// setIntent(intent);
		Integer clickedPosition = intent.getIntExtra(Const.FRAGMENT_GENRES_CLICK_POSITION, -1);
		if (clickedPosition != null && clickedPosition != -1) {
			currentGenresClickedPosition = clickedPosition;
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
			Boolean enableAnnotation = prefs.getBoolean("annotationPref", false);
			fragmentBooks.refreshListViewWithId(clickedPosition, enableAnnotation);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		FragmentTransaction ft = getFragmentManager().beginTransaction();
		FragmentManager fm = getFragmentManager();
		if (isOrientationLanscape()) {
			ft.add(R.id.layout1, fragmentGenres);
			ft.add(R.id.layout2, fragmentBooks);
			ft.commit();
		} else {
			ft.add(R.id.activity_main_tablet_parent_view, fragmentGenres);
			ft.commit();
		}
		fm.executePendingTransactions();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(intentReceiver);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main_activity_menu, menu);
		MenuItem settings = menu.findItem(R.id.main_menu_settings);
		MenuItem updateBooks = menu.findItem(R.id.main_menu_update);
		sortByBall = menu.findItem(R.id.main_menu_sort_by_ball);
		sortByDate = menu.findItem(R.id.main_menu_sort_by_date);

		settings.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				startActivity(new Intent(AcMainTablet.this, PrefAcSamizdat.class));
				return false;
			}
		});

		updateBooks.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem arg0) {
				startService(new Intent(AcMainTablet.this, SrvUpdate.class));
				progressDialog = ProgressDialog.show(AcMainTablet.this, AcMainTablet.this.getString(R.string.UPDATING_BOOKS), AcMainTablet.this.getString(R.string.WAIT_FEW_SECONDS), true);
				return false;
			}
		});

		
		sortByBall.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				sortByBall.setChecked(!sortByBall.isChecked());

				if (sortByBall.isChecked() && sortByDate.isChecked()) {
					fragmentBooks.getFragmentBooksAdapter().refreshListViewWithIdAndSortOrder(currentGenresClickedPosition, Const.DATE + " desc" + ", " + Const.BALL + " desc");
				}
				if (!sortByBall.isChecked() && sortByDate.isChecked()) {
					fragmentBooks.getFragmentBooksAdapter().refreshListViewWithIdAndSortOrder(currentGenresClickedPosition, Const.DATE + " desc");
				}
				if (sortByBall.isChecked() && !sortByDate.isChecked()) {
					fragmentBooks.getFragmentBooksAdapter().refreshListViewWithIdAndSortOrder(currentGenresClickedPosition, Const.BALL + " desc");
				}
				if (!sortByBall.isChecked() && !sortByDate.isChecked()) {
					fragmentBooks.getFragmentBooksAdapter().refreshListViewWithIdAndSortOrder(currentGenresClickedPosition, null);
				}
				return false;
			}
		});

		sortByDate.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {

				sortByDate.setChecked(!sortByDate.isChecked());

				if (sortByBall.isChecked() && sortByDate.isChecked()) {
					fragmentBooks.getFragmentBooksAdapter().refreshListViewWithIdAndSortOrder(currentGenresClickedPosition, Const.BALL + " desc" + ", " + Const.DATE + " desc");
				}
				if (!sortByBall.isChecked() && sortByDate.isChecked()) {
					fragmentBooks.getFragmentBooksAdapter().refreshListViewWithIdAndSortOrder(currentGenresClickedPosition, Const.DATE + " desc");
				}
				if (sortByBall.isChecked() && !sortByDate.isChecked()) {
					fragmentBooks.getFragmentBooksAdapter().refreshListViewWithIdAndSortOrder(currentGenresClickedPosition, Const.BALL + " desc");
				}
				if (!sortByBall.isChecked() && !sortByDate.isChecked()) {
					fragmentBooks.getFragmentBooksAdapter().refreshListViewWithIdAndSortOrder(currentGenresClickedPosition, null);
				}
				return false;
			}
		});

		return true;
	}

	public void hideSortMenu() {
		sortByBall.setVisible(false);
		sortByDate.setVisible(false);
		sortByBall.setChecked(false);
		sortByDate.setChecked(false);
	}

	public void showSortMenu() {
		sortByBall.setVisible(true);
		sortByDate.setVisible(true);
	}

	private Boolean isOrientationLanscape() {
		int orientation = getResources().getConfiguration().orientation;
		if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
			return true;
		} else {
			return false;
		}
	}
	
	BroadcastReceiver	intentReceiver	= new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String serviceUpdateStoped = intent.getStringExtra(Const.SERVICE_UPDATE_STOPED);
			Integer loadingPercents = intent.getIntExtra(Const.UPDATE_LOADING_PERCENTS, -1);

			if(loadingPercents != -1){
				progressDialog.setMessage(AcMainTablet.this.getString(R.string.WAIT_FEW_SECONDS) + " " + String.valueOf(loadingPercents) + "%");
			}
			if (serviceUpdateStoped != null && serviceUpdateStoped.equals(Const.SERVICE_UPDATE_STOPED)) {
				progressDialog.dismiss();
				progressDialog.cancel();
			}
		}
	};
}
